package com.smbms.filter;

import cn.hutool.core.util.ObjectUtil;
import com.smbms.pojo.User;
import com.smbms.utils.Constant;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 描述
 * @Author 羽落陌殇
 * @Date 2021/7/19 8:40
 * @Version 1.0.0
 */
public class SystemFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 过滤器, 从Session中获取用户
        User user = (User) req.getSession().getAttribute(Constant.USER_SESSION);
        if (ObjectUtil.isNull(user)) {
            resp.sendRedirect(req.getServletContext().getContextPath() + "/error.jsp");
        } else {
            chain.doFilter(request, response); // 此处注意使用的是方法中的形参, 不是转换后的变量
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
